<template>
	<view class="page">
		<view style="height: 120rpx;"></view>
		<view class="pic-box">
			<image style="width: 360rpx;height: 360rpx;border-radius: 50%;margin: 60rpx;" :src="meditation.icon_url"></image>
		</view>
		<view class="train-name">{{meditation.title}}</view>
		<view style="position: fixed;bottom: 0;width: 750rpx;display: flex;flex-direction: column;align-items: center;">
			<view style="width: 680rpx;">
				<u-slider v-model="sliderValue" :min="0" :max="maxLen" @change="change" activeColor="#0b2bff"></u-slider>
			</view>
			<view style="margin-top: 30rpx;margin-bottom: 50rpx;">{{nowTime}}/{{allTimeStr}}</view>
			<image @click="toPlay()" v-show="isplay" class="palyIcon" src="@/static/images/pause.png"></image>
			<image @click="toPlay()" v-show="!isplay" class="palyIcon" src="@/static/images/play.png"></image>
			<view style="height: 50rpx;"></view>
		</view>
		<view style="height: 120rpx;"></view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		computed:{
			...mapState(['member','player','timer','nowTime','sliderValue'])
		},
		data() {
			return {
				isEnd:false,
				isplay:false,
				maxLen:100,
				value:0,
				trainName:"",
				audioUrl:"",
				trainName: '',
				meditation:{},
				allTime: '',
				press: 0,
				// nowTime: "0:00",
				startTime: '',
				allTimeStr:"",
				// palyer:null,
				// timer:null,
				isStop:true,
				palyinfo:{
					title:"",
					src:"",
					singer:"",
					coverImgUrl:""
				}
			}
		},
		onLoad(opt) {
			getApp().globalData.player = uni.getBackgroundAudioManager()||null;
			this.palyer = uni.getBackgroundAudioManager()||null;
			
			// #ifdef H5
			getApp().globalData.player = uni.getBackgroundAudioManager();
			this.palyer = uni.getBackgroundAudioManager();
			// #endif
			
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('datas', (data) => {
				this.meditation = data;
				let time = data.audio_duration; //获取总播放时间
				console.log(time);
				
				console.log(this.times(time));
				
				this.allTimeStr = this.times(time);
				if(getApp().globalData.audioId == data.audio_id){
					return;
				}else{
					uni.removeStorageSync('palyTime');
				}
				this.nowTime = "0:00";
				this.palyer.stop();
				if(data.location){
					getApp().globalData.audioId = data.audio_id;
					this.palyinfo.title = data.title;
					this.palyinfo.singer = "";
					this.palyinfo.coverImgUrl = data.icon_url;
					this.palyinfo.src = data.audioUrl;
					getApp().globalData.palyinfo = this.palyinfo;
					return;
				}
				uni.$u.http.post('/client/serviceResource',{
					"data":JSON.stringify({
						audio_id: parseInt(opt.id)
					}),
					"method":"heartide.bixin.audio.playurl"
				},{
					 header: {
						 appId:'bixin_openApi_v1',
						 appKey:'KlaWySuV_j1JcLa-X3UI'
					 }
				}).then(res => {
					if (res.code == '0') {
						let reslist = JSON.parse(res.data)
						this.palyinfo.title = this.meditation.title;
						this.palyinfo.singer = "";
						this.palyinfo.coverImgUrl = this.meditation.icon_url;
						this.palyinfo.src = reslist.audio_play_url;
						getApp().globalData.palyinfo = this.palyinfo;
						getApp().globalData.audioId = opt.id;
						let time = reslist.audio_duration; //获取总播放时间
						if (!time) {
							time = 0;
						}
						let minutes = parseInt(time / 59);
						if (minutes < 10) {
							minutes = "0" + minutes;
						}
						let second = Math.round(time % 59);
						if (second < 10) {
							second = "0" + second;
						}
						let allTime = minutes + ":" + second;
						this.allTime = allTime;
					}
				}).catch(e => {
					this.$toast('网络错误！')
				})
			})
			this.palyer.onPlay(()=>{
				this.isplay = true;
				this.isStop = false;
				
				if(this.$store.state.timer==0){
					this.$store.state.timer = setInterval(()=>{
						// console.log(this.palyer.currentTime);
						this.$store.state.nowTime = this.times(this.palyer.currentTime)
						this.$store.state.sliderValue = parseInt(this.palyer.currentTime/this.palyer.duration*100)
						// if(this.isStop){
						// 	this.nowTime = "0:00";
						// 	this.value = 0;
						// }
						// console.log("nowTime",this.nowTime);
					},1000)
				}
				// let mun = parseInt(uni.getBackgroundAudioManager().duration/60)
				// console.log(uni.getBackgroundAudioManager().duration,"---",mun,"分钟");
			})
			this.palyer.onStop(()=>{
				this.isplay = false;
				this.isStop = true;
				clearInterval(this.$store.state.timer)
				this.$store.state.timer = 0;
				this.$store.state.sliderValue = 0;
				this.$store.state.nowTime = '0:00'
				
				uni.removeStorageSync('palyTime');
			})
			this.palyer.onEnded(()=>{
				console.log("onEnd");
				this.isplay = false;
				console.log(this.isplay);
				clearInterval(this.$store.state.timer)
				this.$store.state.timer = 0;
				this.$store.state.sliderValue = 0;
				this.$store.state.nowTime = '0:00'
				this.addTrain()
				
				this.isStop = true;
			})
			this.palyer.onPause(()=>{
				clearInterval(this.$store.state.timer)
				this.$store.state.timer = 0;
				this.isplay = false;
			})
			this.palyer.onError(()=>{
				uni.showModal({
					showCancel:false,
					content:"音频播放错误！"
				})
			})
		},
		onUnload() {
			if(this.palyer.paused === false){
				uni.removeStorageSync('palyTime');
			}
		},
		onShow() {
			this.$store.state.palyer = uni.getBackgroundAudioManager()||null;
			
			// #ifdef H5
			this.$store.state.palyer = uni.createInnerAudioContext();
			// #endif
			
			if(this.palyer.paused === true){
				this.isplay = false;
			}
			if(this.palyer.paused === false){
				this.isplay = true;
			}
		},
		methods: {
			addTrain(){
				let type = 'train';
				let startTime = uni.getStorageSync('palyTime');
				let start_time = parseInt(startTime/1000)
				let end_time = parseInt(new Date().getTime()/1000)
				if(!end_time || !start_time || Math.abs(end_time-start_time)>7200 || start_time == '0' || start_time == 0){
					return this.$model("系统错误请重试")
				}
				if(end_time-start_time<10){
					return this.$model("练习时间过短~")
				}
				uni.removeStorageSync('palyTime');
				if(this.member.imei){
					uni.$u.http.post('/client/add_train',{phone:this.member.phone,imei:this.member.imei,start_time,end_time,type,name:this.meditation.title}).then(res=>{
						if(res.status == 200){
							uni.redirectTo({
								url:'/pagesA/pages/testMain/testReport?new=1&id='+res.data.trainData[0].id,
								// success: (res) => {
								// 	res.eventChannel.emit('trainData', res.data.trainData[0])
								// }
							})
						}else{
							return this.$model("系统错误请重试")
						}
					})
				}
			},
			toPlay(){
				this.palyer = uni.getBackgroundAudioManager()||null;
				// #ifdef H5
				this.palyer = uni.getBackgroundAudioManager();
				// #endif
				
				if(this.isStop){
					this.palyer.title = getApp().globalData.palyinfo.title;
					this.palyer.singer = "-"
					this.palyer.coverImgUrl = getApp().globalData.palyinfo.coverImgUrl
					this.palyer.src = getApp().globalData.palyinfo.src;
					uni.setStorageSync('palyTime',new Date().getTime())
				}
				if(this.palyer.paused){
					this.palyer.play();
				}else{
					this.palyer.pause();
				}
			},
			change(index){
				this.palyer.seek(parseInt(index/100*this.palyer.duration))
			},
			times(totalSeconds){
				// console.log("totalSeconds:",totalSeconds);
				if(isNaN(totalSeconds)){
					// console.log('0:00');
					return '0:00'
				}
				const minutes = Math.floor(parseInt(totalSeconds) / 60);
				const seconds = parseInt(totalSeconds) % 60;
				function padTo2Digits(num) {
				  return num.toString().padStart(2, '0');
				}
				const result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
				return result;
			}
		}
	}
</script>

<style>
	.page{
		display: flex;
		justify-content: flex-end;
		flex-direction: column;
		align-items: center;
	}
	.palyIcon{
		width: 120rpx;
		height: 120rpx;
	}
	.pic-box{
		width: 480rpx;
		height: 480rpx;
		margin: 0 auto 30px;
		border-radius: 50%;
		background-image: linear-gradient(to right bottom,#262324,#797879);
	}
	.train-name{
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #2e2e2e;
		font-weight: 700;
		font-size: 48rpx;
		padding-bottom: 120rpx;
	}
</style>